# encoding:utf-8
"""
===============***===============
Auther : Hsir
Date   : 2022 - 11 - 18   16:29
File   : interface_login.py
===============***===============
"""
import json
import flask
from autotest03.comms.dbutils import DBUtils




app = flask.Flask(__name__)


@app.route("/login", methods=["get", "post"])
def login():
    data = flask.request.values.to_dict()
    if 'username' not in data:
        return json.dumps({"code": 101, "msg": "请输入用户名!"}, ensure_ascii=False)
    elif 'password' not in data:
        return json.dumps({"code": 102, "msg": "请输入登录密码!"}, ensure_ascii=False)
    name = data["username"]
    passwd = data["password"]
    if len(name) == 0:
        return json.dumps({"code": 103, "msg": "用户名不能为空!"}, ensure_ascii=False)
    elif len(passwd) == 0:
        return json.dumps({"code": 104, "msg": "登录密码不能为空!"}, ensure_ascii=False)
    else:
        db = DBUtils()
        user_count = db.find_count("select name,passwd from tb_user where name=%s", (name,))
        # 此处的businessdb可以在此模板引用前标明，也可以在模板DBUtils中的self conn中添加db=DBUtils共同引用
        user = db.find_one("select name,passwd from tb_user where name=%s", (name,))
        if user_count < 1:
            db.close()
            return json.dumps({"code": 105, "msg": "用户名错误!"}, ensure_ascii=False)
        elif passwd != user[1]:
            db.close()
            return json.dumps({"code": 106, "msg": "用户密码错误!"}, ensure_ascii=False)
        elif name in user and passwd in user:
            db.close()
            return json.dumps({"code": 666, "msg": "登陆成功!"}, ensure_ascii=False)
        else:
            db.close()
            return json.dumps({"code": 444, "msg": "登录失败,环境异常,请联系管理员!"},
                              ensure_ascii=False)


if __name__ == '__main__':
    app.run(port=6669)
